package cn.hgpu.controller;

import cn.hgpu.domain.News;
import cn.hgpu.domain.UserInfo;
import cn.hgpu.service.NewsService;


import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
public class NewsController {

    @Autowired
    private NewsService newsService;

    //查询所有新闻信息并发送到新闻页面
    @RequestMapping("/newsinfo")
    public ModelAndView findAllNews() {

        List<News> newsList = newsService.findAllNews();

        ModelAndView modelAndView = new ModelAndView();

        modelAndView.addObject("newsList", newsList);
        modelAndView.setViewName("newlist");

        return modelAndView;
    }

    //跳到发布新闻页面
    @RequestMapping("/addnews")
    public String addNews() {

        return "addnew";
    }

    @RequestMapping("/addnewsinfo")
    public String addNewsInfo(@RequestBody News news, ServletResponse response) {

        int rows = newsService.addNews(news);

        if (rows > 0) {//添加成功
            JSONObject json = new JSONObject();
            json.put("success", "数据添加成功！！");

            // 回调
            try {
                response.getWriter().print(json);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }
}